package com.lagou.controller;

import com.lagou.client.CodeFeignClient;
import com.lagou.pojo.Token;
import com.lagou.pojo.User;
import com.lagou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import util.ServiceCommonUtil;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户微服务控制层类

 */
@RestController
@RequestMapping("/api/user")
@RefreshScope
public class UserController {

    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    private UserService userService;

    @Autowired
    private CodeFeignClient codeFeignClient;

    @GetMapping("/getApplicationName")
    public String getApplicationName() {
        return applicationName;
    }

    /**
     * 注册的方法
     * @param email 邮箱地址
     * @param password 密码
     * @param code 验证码
     * @return 注册结果
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable String email, @PathVariable String password, @PathVariable String code, HttpServletResponse response) {
        try {
            //调用验证码微服务的校验验证码的接口,校验验证码是否正确,是否超时
            boolean checkResult = codeFeignClient.validate(email, code);
            //校验通过后将用户保存到数据库
            if(checkResult) {
                User user = new User();
                user.setEmail(email);
                user.setPassword(password);
                userService.saveUser(user);
                setResultInfoToCookie("0", response, email);
                return true;
            } else {
                setResultInfoToCookie("1", response, "验证码错误!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 登录的方法
     * @param email 邮箱地址
     * @param password 密码
     * @param response 响应对象
     * @return 验证结果
     */
    @GetMapping("/login/{email}/{password}")
    public boolean login(@PathVariable String email, @PathVariable String password, HttpServletResponse response) {
        try {
            //验证邮箱和密码
            User conditionUser = new User();
            conditionUser.setEmail(email);
            conditionUser.setPassword(password);
            User user = userService.getUserByCondition(conditionUser);
            if(user != null) {
                setResultInfoToCookie("0", response, email);
                return true;
            } else {
                setResultInfoToCookie("1", response, "邮箱或密码错误!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 验证邮箱是否注册的方法
     * @param email 邮箱地址
     * @param response 响应对象
     * @return 验证结果
     */
    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email, HttpServletResponse response) {
        try {
            //验证邮箱和密码
            User conditionUser = new User();
            conditionUser.setEmail(email);
            User user = userService.getUserByCondition(conditionUser);
            if(user != null) {
                setResultInfoToCookie("1", response, "邮箱已注册!");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据Token查询⽤户邮箱地址的方法
     * @param token 令牌
     * @return 邮箱地址
     */
    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {
        Token conditionToken = new Token();
        conditionToken.setToken(token);
        return userService.info(conditionToken);
    }

    public void setResultInfoToCookie(String result, HttpServletResponse response, String... args) {
        if(result.equals("0")) {
            //生成Token
            String tempToken = ServiceCommonUtil.generateToken();
            //将Token保存到数据库
            Token token = new Token();
            token.setEmail(args[0]);
            token.setToken(tempToken);
            userService.saveToken(token);
            //将Token和Email添加到Cookies
            Cookie tokenCookie = new Cookie("token", tempToken);
            tokenCookie.setPath("/");
            Cookie emailCookie = new Cookie("email", args[0]);
            emailCookie.setPath("/");
            response.addCookie(tokenCookie);
            response.addCookie(emailCookie);
        } else {
            Cookie msgCookie = new Cookie("msg", args[0]);
            msgCookie.setPath("/");
            response.addCookie(msgCookie);
        }
    }
}
